/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.web;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.security.shiro.session.SessionDAO;
import com.thinkgem.jeesite.common.servlet.ValidateCodeServlet;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.CookieUtils;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.UserAgentUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.cms.entity.Site;
import com.thinkgem.jeesite.modules.cms.utils.CmsUtils;
import com.thinkgem.jeesite.modules.gt.entity.GtInfoDeliver;
import com.thinkgem.jeesite.modules.gt.entity.GtPostPeople;
import com.thinkgem.jeesite.modules.gt.entity.GtWorkReport;
import com.thinkgem.jeesite.modules.gt.service.GtAnalysisService;
import com.thinkgem.jeesite.modules.gt.service.GtInfoDeliverService;
import com.thinkgem.jeesite.modules.gt.service.GtPostPeopleService;
import com.thinkgem.jeesite.modules.gt.service.GtWorkReportService;
import com.thinkgem.jeesite.modules.sys.dao.MenuDao;
import com.thinkgem.jeesite.modules.sys.entity.Area;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.security.FormAuthenticationFilter;
import com.thinkgem.jeesite.modules.sys.security.SystemAuthorizingRealm.Principal;
import com.thinkgem.jeesite.modules.sys.service.AreaService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 登录Controller
 * @author ThinkGem
 * @version 2013-5-31
 */
@Controller
public class LoginController extends BaseController{
	
	@Autowired
	private SessionDAO sessionDAO;
	
	@Autowired
	private GtAnalysisService gtAnalysisService;
	
	@Autowired
	private MenuDao menuDao;
	
	@Autowired
	private GtWorkReportService gtWorkReportService;
	
	@Autowired
	private GtInfoDeliverService gtInfoDeliverService;
	
	@Autowired
	private AreaService areaService;
	
	@Autowired
	private GtPostPeopleService gtPostPeopleService;
	
	/**
	 * 管理登录
	 */
	@RequestMapping(value = "${adminPath}/login", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
		Principal principal = UserUtils.getPrincipal();

		if (logger.isDebugEnabled()){
			logger.debug("login, active session size: {}", sessionDAO.getActiveSessions(false).size());
		}
		
		// 如果已登录，再次访问主页，则退出原账号。
		if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))){
			CookieUtils.setCookie(response, "LOGINED", "false");
		}
		
		// 如果已经登录，则跳转到管理首页
		if(principal != null && !principal.isMobileLogin()){
			return "redirect:" + adminPath;
		}
		
		// mod by zad 2018-03-27 退出后到前台登陆页面
		// return "modules/sys/sysLogin";
		return "modules/gt/basic/login";
	}
	
	/**
	 * 管理登录
	 */
	@RequestMapping(value = "${adminPath}/loginOut", method = RequestMethod.GET)
	public String loginOut(HttpServletRequest request, HttpServletResponse response, Model model) {
		Principal principal = UserUtils.getPrincipal();

		// 如果已登录，再次访问主页，则退出原账号。
		if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))){
			CookieUtils.setCookie(response, "LOGINED", "false");
		}
		
		// 如果已经登录，则跳转到管理首页
		if(principal != null && !principal.isMobileLogin()){
			UserUtils.getSubject().logout();
		}
		
		// mod by zad 2018-03-27 退出后到前台登陆页面
		// return "modules/sys/sysLogin";
		return "modules/gt/basic/login";
	}

	/**
	 * 登录失败，真正登录的POST请求由Filter完成
	 */
	@RequestMapping(value = "${adminPath}/login", method = RequestMethod.POST)
	public String loginFail(HttpServletRequest request, HttpServletResponse response, Model model) {
		Principal principal = UserUtils.getPrincipal();
		
		String userType = request.getParameter("userType");
		
		// 如果已经登录，则跳转到管理首页
		if(principal != null){
			// return "redirect:" + adminPath;
			if("front".equals(userType)){
				return "redirect:" + frontPath+"/";
			}else if("weixin".equals(userType)){
				Site site = CmsUtils.getSite(Site.weixinSiteId());
				model.addAttribute("site", site);
				// return "redirect:" + frontPath+"/" + site.getTheme() + "/frontMyIndex?siteId=" + Site.weixinSiteId();
				return "redirect:" + frontPath + "/myIndex?siteId=" + Site.weixinSiteId();
				
			}else{
				return "redirect:" + adminPath;
			}
		}

		String username = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
		boolean rememberMe = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM);
		boolean mobile = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM);
		String exception = (String)request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		String message = (String)request.getAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM);
		
		if (StringUtils.isBlank(message) || StringUtils.equals(message, "null")){
			message = "用户或密码错误, 请重试.";
		}

		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, username);
		model.addAttribute(FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM, rememberMe);
		model.addAttribute(FormAuthenticationFilter.DEFAULT_MOBILE_PARAM, mobile);
		model.addAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME, exception);
		model.addAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM, message);
		// add by zad 2018-03-27 提示框样式控制
		model.addAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_TYPE, "warning");
		
		if (logger.isDebugEnabled()){
			logger.debug("login fail, active session size: {}, message: {}, exception: {}", 
					sessionDAO.getActiveSessions(false).size(), message, exception);
		}
		
		// 非授权异常，登录失败，验证码加1。
		if (!UnauthorizedException.class.getName().equals(exception)){
			model.addAttribute("isValidateCodeLogin", isValidateCodeLogin(username, true, false));
		}
		
		// 验证失败清空验证码
		request.getSession().setAttribute(ValidateCodeServlet.VALIDATE_CODE, IdGen.uuid());
		
		// 如果是手机登录，则返回JSON字符串
		/*if (mobile){
	        return renderString(response, model);
		}*/
		
		
		String returnUrl="";
		if("weixin".equals(userType)){
			
			// return "redirect:" + frontPath+"/toLogin?siteId=" + Site.weixinSiteId();
			Site site = CmsUtils.getSite(Site.weixinSiteId());
			model.addAttribute("site", site);
			return "modules/cms/front/themes/" + site.getTheme() + "/frontLogin";
			
		}else{
			
			// mod by zad 2018-03-27 登陆页面修改
			// returnUrl="modules/sys/sysLogin";
			returnUrl= "modules/gt/basic/login";
			
		}
		
		
		return returnUrl;
	}

	/**
	 * 登录成功，进入管理首页
	 */
	 @RequiresPermissions("user")
	 
	@RequestMapping(value = "${adminPath}")
	public String index(Area area,HttpServletRequest request, HttpServletResponse response,String menuId, Model model) {
		Principal principal = UserUtils.getPrincipal();

		
		
		//---------------------------
		/*String date = "2019-01-20 00:00:00";
		//String date = "2019-01-08 22:50:00";
		try {
			Date myDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(date);
			Date now = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(this.menuDao.sysDate().get("now"));
			if(now.after(myDate))
			{
				UserUtils.getSubject().logout();
				return "redirect:" + adminPath + "/login";
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}*/
		//---------------------------
		
		
		
		// 登录成功后，验证码计算器清零
		isValidateCodeLogin(principal.getLoginName(), false, true);
		
		if (logger.isDebugEnabled()){
			logger.debug("show index, active session size: {}", sessionDAO.getActiveSessions(false).size());
		}
		
		// 如果已登录，再次访问主页，则退出原账号。
		if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))){
			String logined = CookieUtils.getCookie(request, "LOGINED");
			if (StringUtils.isBlank(logined) || "false".equals(logined)){
				CookieUtils.setCookie(response, "LOGINED", "true");
			}else if (StringUtils.equals(logined, "true")){
				UserUtils.getSubject().logout();
				return "redirect:" + adminPath + "/login";
			}
		}
		
		// 如果是手机登录，则返回JSON字符串
		if (principal.isMobileLogin()){
			if (request.getParameter("login") != null){
				return renderString(response, principal);
			}
			if (request.getParameter("index") != null){
				return "modules/sys/sysIndex";
			}
			return "redirect:" + adminPath + "/login";
		}
		
//		// 登录成功后，获取上次登录的当前站点ID
//		UserUtils.putCache("siteId", StringUtils.toLong(CookieUtils.getCookie(request, "siteId")));

//		System.out.println("==========================a");
//		try {
//			byte[] bytes = com.thinkgem.jeesite.common.utils.FileUtils.readFileToByteArray(
//					com.thinkgem.jeesite.common.utils.FileUtils.getFile("c:\\sxt.dmp"));
//			UserUtils.getSession().setAttribute("kkk", bytes);
//			UserUtils.getSession().setAttribute("kkk2", bytes);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
////		for (int i=0; i<1000000; i++){
////			//UserUtils.getSession().setAttribute("a", "a");
////			request.getSession().setAttribute("aaa", "aa");
////		}
//		System.out.println("==========================b");
		
		String returnUrl="";
		if("weixin".equals(principal.getUserType())){
			// return "redirect:" + frontPath+"/team/teamIndex";
			return "redirect:" + frontPath+"/myIndex?siteId=" + Site.weixinSiteId();
		}else{
			
			User user = UserUtils.getUser();
			model.addAttribute("user", user);
			model.addAttribute("menuId", menuId);
			
			Map<String,String> map = new HashMap<String, String>();
			String code = user.getArea().getCode();
			map.put("code", code);
			
			String type = user.getArea().getType();
			map.put("level", type);
			
			// add by zad 2018-04-08 经济扶贫林总体进度  面积和人数
			Map<String,String> forestTotalRate = this.gtAnalysisService.forestTotalRate(map);
			model.addAttribute("forestTotalRate", forestTotalRate);
			// add by zad 2018-04-08 经济扶贫林总体进度
			/*Map<String,String> forestPeopleRate = this.gtAnalysisService.forestPeopleRate();
			model.addAttribute("forestPeopleRate", forestPeopleRate);*/
			
			// add by zad 2018-04-08 护林员岗位总体扶贫进度
			Map<String,String> postTotalRate = this.gtAnalysisService.postTotalRate(map);
			model.addAttribute("postTotalRate", postTotalRate);
			
			// add by zad 2018-04-08 企社总体扶贫进度          2018-04-20 企社不再区分是企业还是合作社
			// map.put("type", Constant.Company.COMPANY_TYPE_COMPANY);
			Map<String,String> companyTotalRate = this.gtAnalysisService.companyTotalRate(map);
			model.addAttribute("companyTotalRate", companyTotalRate);
			
			// add by zad 2018 -05-10 手机访问首页时，因为手机首页不需要查询数据，所以直接到手机的首页即可，无需查询数据后到 MobileInterceptor过滤器处理并调转手机首页
			if(UserAgentUtils.isMobileOrTablet(request) && !StringUtils.startsWithIgnoreCase(request.getRequestURI(), "redirect:")){
				String url = request.getRequestURI();
				// pc端和手机端登录页面为同一登录页面，手机登录后直接都手机的登录页面
				if(url.indexOf("gt/basic/login") < 0){
					/*if(url.indexOf("/basic/") > -1)
					{
						url = url.replace("/basic/", "/weixin/");
					}*/
					// modelAndView.setViewName(url);
					return "modules/gt/weixin/index";
				}
			}
			
			/*// 各地市、区县扶贫林进度统计(面积、人数完成进度)
			List<Map<String,String>> forestRegionList = this.gtAnalysisService.forestRegionRate(map);
			model.addAttribute("forestRegionList", forestRegionList);
			
			// 各地市、区县护林员岗位进度统计(人数完成进度)
			List<Map<String,String>> postRegionList = this.gtAnalysisService.postRegionPeopleRate(map);
			model.addAttribute("postRegionList", postRegionList);
			
			// 各地市、区县龙头企业（合作社）进度统计(人数完成进度)
			List<Map<String,String>> companyRegionList = this.gtAnalysisService.companyRegionRate(map);
			model.addAttribute("companyRegionList", companyRegionList);
			
			
			// 各地市、区县     县技术明白人进度统计(人数完成进度)
			map.put("clearType", "4");
			List<Map<String,String>> clearCountyList = this.gtAnalysisService.clearRegionRate(map);
			model.addAttribute("clearCountyList", clearCountyList);
			
			// 各地市、区县     乡镇技术明白人进度统计(人数完成进度)
			map.put("clearType", "5");
			List<Map<String,String>> clearTownList = this.gtAnalysisService.clearRegionRate(map);
			model.addAttribute("clearTownList", clearTownList);
			
			// 各地市、区县     村技术明白人进度统计(人数完成进度)
			map.put("clearType", "6");
			List<Map<String,String>> clearCountryList = this.gtAnalysisService.clearRegionRate(map);
			model.addAttribute("clearCountryList", clearCountryList);*/
			
			
			/*各个地市、区县所有进度统计 add by zad 2018-05-02*/
			map.put("clearType", "4");
			map.put("clearTypeTown", "5");
			map.put("clearTypeCountry", "6");
			List<Map<String,String>> fpRegionAllRateList = this.gtAnalysisService.fpRegionAllRate(map);
			model.addAttribute("fpRegionAllRateList", fpRegionAllRateList);
			
			
			
			GtWorkReport gtWorkReport = new GtWorkReport();
			
			// 工作月报区域限制
			/*gtWorkReport.setMonth(new Date());
			Area userArea = user.getArea();
			String areaType = userArea.getType();
			// 省级账号
			if(Constant.Area.AREA_TYPE_PROVINCE.equals(areaType))
			{
				gtWorkReport.setArea(userArea);
			}else
			// 地市及县级时，按照其上级机构查询（地市账号可以查看同级的工作月报，县级账号只能查看其所属地市的工作月报）
			if(Constant.Area.AREA_TYPE_REGION.equals(areaType) || Constant.Area.AREA_TYPE_COUNTY.equals(areaType))
			{
				gtWorkReport.setArea(userArea.getParent());
			}*/
			
			// 工作月报没有限制，任何人都可以查看，首页默认展示当月月报 add by zad 2018-04-28
			// gtWorkReport.setMonth(new Date());
			
			if(null == gtWorkReport.getArea() || StringUtils.isBlank(gtWorkReport.getArea().getCode()))
			{
				gtWorkReport.setArea(UserUtils.getUser().getArea());
				
			}
			
			// 各地市工作月报
			List<GtWorkReport> workReportList = this.gtWorkReportService.findList(gtWorkReport);
			model.addAttribute("workReportList", workReportList);
			
			
			// 信息宣传不做限制，默认只展示当月提交的信息宣传
			GtInfoDeliver info = new GtInfoDeliver();
			info.setCreateDate(new Date());
			/*Area areaP = new Area();
			areaP.setCode(code);
			info.setArea(areaP);*/
			// 各地市信息宣传
			List<GtInfoDeliver> infoList = this.gtInfoDeliverService.findList(info);
			model.addAttribute("infoList", infoList);
			
			// mod by zad 2018-03-27 修改首页
			returnUrl="modules/gt/basic/index";
			
			if(Global.getIsOpenback())
			{
				returnUrl="modules/sys/sysIndex";
			}
		}
		// return "modules/sys/sysIndex";
		return returnUrl;
	}
	
	 /**
     * 首页导出各地市扶贫进度统计文件
     */
    @RequestMapping("${adminPath}/downLoad")
    public void downLoad(String areaId,GtPostPeople gtPost,String timeStamp, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException{
    	Area area = null;
    	if("undefined".equals(areaId))
    	{
    		areaId = "";
    	}
    	if(!StringUtils.isEmpty(areaId))
		{
			area = this.areaService.get(areaId);
		}
    	
    	response.setCharacterEncoding("utf-8");
    	String fileName = UserUtils.getUser().getArea().getName() + Global.getConfig("exportHelpProgressFileName");
    	
    	User user = UserUtils.getUser();
    	String type = user.getArea().getType();
    	
    	if(null != area)
    	{
    		fileName = area.getName() + Global.getConfig("exportHelpProgressFileName");
    	}
    	String [] nameArr = fileName.split("\\{1\\}");
    	if("2".equals(type)){
    		fileName = nameArr[0] + "地市" + nameArr[1];
        }
        if("3".equals(type)){
        	fileName = nameArr[0] + "区县" + nameArr[1];
        }
        if("4".equals(type)){
        	fileName = nameArr[0] + "乡镇" + nameArr[1];
        }
    	
    	fileName += DateUtils.getDate();
        // fileName = URLEncoder.encode(fileName, "UTF-8");
    	
    	// response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
        
        SXSSFWorkbook wb = new SXSSFWorkbook(-1);
        // turn off auto-flushing and accumulate all rows in memory  
        wb.setCompressTempFiles(true); //使用gzip压缩,减小空间占用  
        Sheet sh = wb.createSheet("扶贫进度统计信息");
        OutputStream out = new BufferedOutputStream(response.getOutputStream());
        try { //从数据库中得到结果  
        	
        	
        	
            /*各个地市、区县所有进度统计 add by zad 2018-05-02*/
        	
        	Map<String,String> map = new HashMap<String, String>();
			String code = user.getArea().getCode();
			map.put("code", code);
			
			map.put("level", type);
			map.put("clearType", "4");
			map.put("clearTypeTown", "5");
			map.put("clearTypeCountry", "6");
			List<Map<String,String>> fpRegionAllRateList = this.gtAnalysisService.fpRegionAllRate(map);
			
            
            if(null == fpRegionAllRateList || fpRegionAllRateList.size() < 1)
            {
	            sh.setColumnWidth(0, 50 * 256);
	        	Row rowHeader = sh.createRow(0);
	            Cell cellHeader = rowHeader.createCell(0);
	            cellHeader.setCellValue("信息提示");
	            
	            Row row = sh.createRow(1);
	            Cell cell = row.createCell(0);  
	            cell.setCellValue("没有找到相关条件的数据。");  
	            
	            ((SXSSFSheet) sh).flushRows();
	            
	            CookieUtils.rememberCookieToken(timeStamp,request,response);
	            //统一写出方法
	            FileUtils.writeWb(wb,out);
            }else
            {
	            
	            //设置每一列的宽度,注意 要乘以256,因为1代表excel中一个字符的1/256的宽度  
	            sh.setColumnWidth(0, 10 * 256);
	            sh.setColumnWidth(1, 20 * 256);
	            sh.setColumnWidth(2, 20 * 256);
	            sh.setColumnWidth(3, 20 * 256);
	            sh.setColumnWidth(4, 20 * 256);
	            sh.setColumnWidth(5, 20 * 256);
	            sh.setColumnWidth(6, 20 * 256);
	            sh.setColumnWidth(7, 20 * 256);
	            sh.setColumnWidth(8, 20 * 256);
	            sh.setColumnWidth(9, 20 * 256);
	            Row rowHeader = sh.createRow(0);
	            /*CellStyle headerStyle = rowHeader.getRowStyle();
	            headerStyle.setAlignment(CellStyle.ALIGN_CENTER);*/
	            Cell cellHeader = rowHeader.createCell(0);
	            cellHeader.setCellValue("单位");
	            cellHeader = rowHeader.createCell(1);
	            cellHeader.setCellValue("经济林面积（亩）");
	            cellHeader = rowHeader.createCell(2);
	            cellHeader.setCellValue("经济林人数");
	            cellHeader = rowHeader.createCell(3);
	            cellHeader.setCellValue("护林员岗位人数");
	            cellHeader = rowHeader.createCell(4);
	            cellHeader.setCellValue("企业(合作社)数量");
	            
	            cellHeader = rowHeader.createCell(5);
	            if("2".equals(type)){
	            	cellHeader.setCellValue("市科技下乡次数");
	            }
	            if("3".equals(type)){
	            	cellHeader.setCellValue("县科技下乡覆盖村数");
	            }
	            if("4".equals(type)){
	            	cellHeader.setCellValue("科技下乡覆盖村数");
	            }
	            
	            cellHeader = rowHeader.createCell(6);
	            cellHeader.setCellValue("县科技下乡覆盖村数");
	            
	            cellHeader = rowHeader.createCell(7);
	            cellHeader.setCellValue("县技术专家人数");
	            cellHeader = rowHeader.createCell(8);
	            cellHeader.setCellValue("乡镇技术员人数");
	            cellHeader = rowHeader.createCell(9);
	            cellHeader.setCellValue("村技术明白人数");
	            
	            // 只取5000条数据
	            /*if(null != list && list.size() > Constant.Join.JOIN_EXPORT_MOST_ROWS)
	            {
	            	list.subList(Constant.Join.JOIN_EXPORT_MOST_ROWS, list.size()).clear();
	            }*/
	            
	            // 序号
	            int size = fpRegionAllRateList.size();
	            for(int i = 0; i < size; i++) {
	            	
	            	// 当前护林员岗位
	            	Map<String,String> fpRate = fpRegionAllRateList.get(i);
	            	
	                Row row = sh.createRow(i+1);
	                Cell cell = row.createCell(0);  
	                cell.setCellValue(fpRate.get("name"));
	                
	                cell = row.createCell(1);
	                cell.setCellValue(String.valueOf(fpRate.get("realArea")) + "(" + String.valueOf(fpRate.get("forestRate")) + "%)");
	                
	                cell = row.createCell(2);
	                cell.setCellValue(String.valueOf(fpRate.get("realForestPeople")) + "(" + String.valueOf(fpRate.get("forestPeopleRate")) + "%)");
	                cell = row.createCell(3);
	                	String areaCode = fpRate.get("code");
	                	if(areaCode.equals("sd.dy") || areaCode.equals("sd.dz") || areaCode.equals("sd.hz"))
	                	{
	                		//cell.setCellValue("----"); 
	                		cell.setCellValue(String.valueOf(fpRate.get("realPostPeople")) + "(----)"); 
	                	}else
	                	{
	                		cell.setCellValue(String.valueOf(fpRate.get("realPostPeople")) + "(" + String.valueOf(fpRate.get("postRate")) + "%)"); 
	                	}
	                cell = row.createCell(4);
	                cell.setCellValue(String.valueOf(fpRate.get("realCompany")) + "(" + String.valueOf(fpRate.get("companyRate")) + "%)");
	                cell = row.createCell(5);
	                cell.setCellValue(String.valueOf(fpRate.get("real")) + "(" + String.valueOf(fpRate.get("countryRate")) + "%)");
	                
	                cell = row.createCell(6);
	                	String areaType = user.getArea().getType();
	                	if("2".equals(areaType))
	                	{
	                		cell.setCellValue(String.valueOf(fpRate.get("countryCoverReal")) + "(" + String.valueOf(fpRate.get("countryCoverRate")) + "%)");
	                	}else
	                	{
	                		cell.setCellValue("----");
	                	}
	                	
	                
	                cell = row.createCell(7);
	                cell.setCellValue(String.valueOf(fpRate.get("realClear")) + "(" + String.valueOf(fpRate.get("clearRate")) + "%)");
	                cell = row.createCell(8);
	                cell.setCellValue(String.valueOf(fpRate.get("realTownClear")) + "(" + String.valueOf(fpRate.get("clearTownRate")) + "%)");
	                cell = row.createCell(9);
	                cell.setCellValue(String.valueOf(fpRate.get("realCountryClear")) + "(" + String.valueOf(fpRate.get("clearCountryRate")) + "%)");
	      
	                /*if(i > 0 && (i % 1000 == 0)) {  
	                    ((SXSSFSheet) sh).flushRows();  
	                } */
	            }
	            
	            ((SXSSFSheet) sh).flushRows();
	            
	            CookieUtils.rememberCookieToken(timeStamp,request,response);
	            //统一写出方法
	            FileUtils.writeWb(wb,out);
	            
            }
        } catch(Exception e) {
        	sh.setColumnWidth(0, 50 * 256);
        	Row rowHeader = sh.createRow(0);
            Cell cellHeader = rowHeader.createCell(0);
            cellHeader.setCellValue("信息提示");
            
            Row row = sh.createRow(1);
            Cell cell = row.createCell(0);  
            cell.setCellValue("导出失败，请联系管理员。错误信息：" + e.getMessage());  
            
            e.printStackTrace();
            ((SXSSFSheet) sh).flushRows();
            
            CookieUtils.rememberCookieToken(timeStamp,request,response);
            //统一写出方法
            FileUtils.writeWb(wb,out);
        }  
     // 保存日志
     request.setAttribute("title", "用户" + UserUtils.getUser().getLoginName() + "导出了文件：" + fileName);
    }
	 
	/**
	 * 获取主题方案
	 */
	@RequestMapping(value = "/theme/{theme}")
	public String getThemeInCookie(@PathVariable String theme, HttpServletRequest request, HttpServletResponse response){
		if (StringUtils.isNotBlank(theme)){
			CookieUtils.setCookie(response, "theme", theme);
		}else{
			theme = CookieUtils.getCookie(request, "theme");
		}
		return "redirect:"+request.getParameter("url");
	}
	
	/**
	 * 是否是验证码登录
	 * @param useruame 用户名
	 * @param isFail 计数加1
	 * @param clean 计数清零
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static boolean isValidateCodeLogin(String useruame, boolean isFail, boolean clean){
		Map<String, Integer> loginFailMap = (Map<String, Integer>)CacheUtils.get("loginFailMap");
		if (loginFailMap==null){
			loginFailMap = Maps.newHashMap();
			CacheUtils.put("loginFailMap", loginFailMap);
		}
		Integer loginFailNum = loginFailMap.get(useruame);
		if (loginFailNum==null){
			loginFailNum = 0;
		}
		if (isFail){
			loginFailNum++;
			loginFailMap.put(useruame, loginFailNum);
		}
		if (clean){
			loginFailMap.remove(useruame);
		}
		return loginFailNum >= 3;
	}
}
